package com.rtmart.imageupload.controller.item;

import com.rtmart.imageupload.Tools.DateTools;
import com.rtmart.imageupload.Tools.FileTools;
import com.rtmart.imageupload.entity.Item;
import com.rtmart.imageupload.repository.ItemRepository;
import com.rtmart.imageupload.repositoryImp.ItemRepositoryImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/item/")
@PreAuthorize("hasAnyRole('ROLE_root','ROLE_admin')")
public class ItemController {

    @Value("${item.location}")
    private String basePath;

    @Autowired
    private ItemRepository itemRepository;
    @Autowired
    private ItemRepositoryImp itemRepositoryImp;

    @GetMapping("edit")
    public String addItem(Model model) {
        Item item = new Item();
        item.setLastDate(new Date());
        model.addAttribute("item", item);
        return "item/edit";
    }


    @GetMapping("edit/{id}")
    public String editItem(@PathVariable Long id, Model model) {
        model.addAttribute("imageUrlList", FileTools.imageUrlList(new File(basePath + itemRepository.getOne(id).getNo() + "/")));
        model.addAttribute("item", itemRepository.getOne(id));
        return "item/edit";
    }
    @GetMapping("ajaxUpdate")
    @Transactional
    @ResponseBody
    public Integer ajaxUpdate(String name, String data, Long id){
        return itemRepositoryImp.ajaxUpdate(name, data, id);
    }
    //删除记录入口
/*    @GetMapping("delete/{id}")
    @Transactional
    public String deleteItem(@PathVariable Long id, RedirectAttributes model) {
        Item item = itemRepository.getOne(id);
        File file = new File(basePath + "/" + item.getNo() + "/");
        FileTools.deleteDir(file);

        itemRepository.delete(item);
        model.addFlashAttribute("message", "删除成功");
        return "redirect:/item/list";
    }*/

    @PostMapping("edit")
    @Transactional
    public String editItem(@Validated Item item, BindingResult bindingResult,Model model,RedirectAttributes redirectAttributes,
                           @RequestParam("file") List<MultipartFile> fileList) {
        //错误排查
        if (bindingResult.hasErrors()) {
            return "item/edit";
        }
        //货号，索取，类型，大小检查
        Long id = item.getId();
        if (null == id){
            if (itemRepository.existsByNo(item.getNo())){
                model.addAttribute("errorMessage", "货号:"+ item.getNo() +",已存在，请检查");
                return "item/edit";
            }
        }
        for (MultipartFile tempFile : fileList) {
            if (!tempFile.isEmpty()) {
                String fileType = tempFile.getContentType();
                if (!(fileType.equals("image/jpeg") || fileType.equals("image/gif") || fileType.equals("image/png") || fileType.equals("image/bmp"))) {
                    model.addAttribute("errorMessage",tempFile.getOriginalFilename() + "，文件类型不正确，请上传JPEG,GIF,PNG,BMP格式的图片");
                    return "item/edit";
                }
                if (tempFile.getSize() > 2097152){
                    model.addAttribute("errorMessage",tempFile.getOriginalFilename() + "，大小超过2MB，请压缩后重新上传");
                    return "item/edit";
                }
            }
        }
        /*else {
            Item oldItem = itemRepository.getOne(id);
            if (itemRepository.existsByIdNotAndNo(id, item.getNo())){
                model.addAttribute("errorMessage", "货号:"+ item.getNo() +",已存在，请检查");
                model.addAttribute("imageUrlList", itemSelectController.imageUrlList(id));
                model.addAttribute("item", oldItem);
                return "item/edit";
            }
            for (MultipartFile tempFile : fileList) {
                if (!tempFile.isEmpty()) {
                    String fileTpye = tempFile.getContentType();
                    if (!(fileTpye.equals("image/jpeg") || fileTpye.equals("image/gif") || fileTpye.equals("image/png"))) {
                        model.addAttribute("errorMessage",tempFile.getOriginalFilename() + "文件类型不正确，请上传JPG,GIF,PNG格式的图片");
                        model.addAttribute("imageUrlList", itemSelectController.imageUrlList(id));
                        model.addAttribute("item", oldItem);
                        return "item/edit";
                    }
                    if (tempFile.getSize() > 2097152){
                        model.addAttribute("errorMessage",tempFile.getOriginalFilename() + "大小超过2MB，请压缩后重新上传");
                        model.addAttribute("imageUrlList", itemSelectController.imageUrlList(id));
                        model.addAttribute("item", oldItem);
                        return "item/edit";
                    }
                }
            }
        }

        if(null != item.getId()){
            //存在记录修改货号
            Item oldItem = itemRepository.getOne(item.getId());
            Integer oldNo = oldItem.getNo();
            if (item.getNo() != oldNo){
                File file = new File(basePath + "/" + oldNo + "/");
                file.renameTo(new File(basePath + "/" + item.getNo() + "/"));
            }
        }
        */
        //建立目录
        File filePath = new File(basePath + item.getNo() + "/");
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        //上传文件
        String imageFilePath = basePath + item.getNo() + "/";
        for (MultipartFile tempFile : fileList) {
            if (tempFile.isEmpty()) continue;
            String imageFileFullPath = imageFilePath + tempFile.getOriginalFilename();
            File file = new File(imageFileFullPath);
            if (file.exists()) {
                for (int i = 1; i <= 100000; i++) {
                    String imageFileName = i + tempFile.getOriginalFilename();
                    imageFileFullPath = imageFilePath + imageFileName;
                    if (!file.exists()) break;
                }
            }

            FileTools.savaFile(tempFile, new File(imageFileFullPath));
        }

        Item item1 = itemRepository.save(item);
        redirectAttributes.addFlashAttribute("message","保存成功！");
        return "redirect:/item/edit/"+item1.getId();
    }

}
